import userManage from '@/api/user';

const getDefaultState = () => {
  return {
    token: '',
    userInfo: JSON.parse(window.localStorage.getItem('userinfo')) || {},
    paging: {
      size: 0,
      num: 0,
    },
  };
};

async function getInfo() {
  return await userManage.getUserInfo();
}
/* async function logout() {
  
} */
const state = getDefaultState();

const getters = {
  getUserInfo(state) {
    return state.userInfo;
  },
  getPaging(state) {
    return state.paging;
  },
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USER_INFO: (state, userInfo) => {
    console.log(userInfo);
    state.userInfo = userInfo;
  },
  SET_PAGING: (state, paging) => {
    state.paging = paging;
  },
};

const actions = {
  setToken({ commit }, token) {
    commit('SET_TOKEN', token);
  },
  setUserInfo({ commit }, userInfo) {
    commit('SET_USER_INFO', userInfo);
  },
  setPaging({ commit }, paging) {
    commit('SET_PAGING', paging);
  },
  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      let result = getInfo();
      result
        .then(async (response) => {
          commit('SET_USER_INFO', { ...response.data });
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  // user logout
  logout() {
    return new Promise((resolve, reject) => {
      userManage
        .loginOut()
        .then(async () => {
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
